
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_audit_app/model/list_view_header_model.dart';
import 'package:flutter_audit_app/model/page_list_bean.dart';
import 'package:flutter_audit_app/net/api_service.dart';
import 'package:flutter_audit_app/net/dio_utils.dart';
import 'package:flutter_audit_app/res/colors.dart';
import 'package:flutter_audit_app/res/gaps.dart';
import 'package:flutter_audit_app/res/strings.dart';
import 'package:flutter_audit_app/res/styles.dart';
import 'package:flutter_audit_app/routes/fluro_navigator.dart';
import 'package:flutter_audit_app/routes/router_path.dart';
import 'package:flutter_audit_app/ui/home/model/user_bean.dart';
import 'package:flutter_audit_app/utils/dialog/dialog_manager.dart';
import 'package:flutter_audit_app/utils/toast.dart';
import 'package:flutter_audit_app/widgets/input_edit_text.dart';
import 'package:flutter_audit_app/widgets/my_app_bar.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class PersonInfoQueryPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PersonInfoQueryState();
}

class _PersonInfoQueryState extends State<PersonInfoQueryPage> {
  ///刷新控制器
  EasyRefreshController _refreshController = EasyRefreshController();

  bool firstRequest = true;

  ///页码
  int _page = 1;

  //总数
  int _count = 0;

  ///控制结束
  bool _enableControlFinish = false;

  List<UserBean> _userList = [];

  @override
  void initState() {
    super.initState();
    //https://www.jianshu.com/p/117b542c98da不包裹会报错
    Future.delayed(Duration.zero, () {
      _requestListBasicInfo(_page);
    });
  }

  ///搜索相关参数
  String inputName;
  String inputIdCard;
  String inputPersonNum;
  String inputSocialCard;

  void _requestListBasicInfo(int page) {
    if (firstRequest) {
      DialogManager.showBasicDialog(context);
    }
    DioUtils.instance.asyncRequestNetwork<PageListBean>(
      Method.get,
      ApiService.query_list_basic_info,
      params: {
        'name': inputName,
        'idCardNo': inputIdCard,
        'basicCode': inputPersonNum,
        'socialSecurityCardNumber': inputSocialCard,
        'size': 20,
        'page': page,
      },
      onSuccess: (response) {
        setState(() {
          _count = response.total;
          _userList.addAll(response.rows);
        });
      },
      onError: (int code, String msg) {
        Toast.show(msg);
      },
      onCompleted: () {
        if (firstRequest) {
          firstRequest = false;
          DialogManager.dismiss();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: Text(Strings.piqTxt),
      ),
      body: Container(
        padding: EdgeInsets.all(width(30)),
        child: Column(
          children: [
            _searchLabel(),
            SizedBox(height: height(30)),
            listViewHeader(list: [
              ListViewHeaderModel(title: Strings.snTxt),
              ListViewHeaderModel(weight: 2, title: Strings.nameTxt),
              ListViewHeaderModel(weight: 4, title: Strings.idCardTxt),
              ListViewHeaderModel(weight: 3, title: Strings.personNoTxt),
              ListViewHeaderModel(weight: 3, title: Strings.socialCardTxt),
              ListViewHeaderModel(weight: 2, title: Strings.operateTxt)
            ]),
            Expanded(
              child: EasyRefresh.custom(
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                controller: _refreshController,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                slivers: <Widget>[
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return getItem(index);
                      },
                      childCount: _userList.length,
                    ),
                  ),
                ],
                emptyWidget: _userList.isEmpty ? Gaps.noDataPlaceholder : null,
                onRefresh: () async {
                  await _refreshData();
                },
                onLoad: () async {
                  await _loadMoreData();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///搜索栏
  Widget _searchLabel() {
    return Row(
      children: [
        InputEditText(
          Strings.nameTxt,
          keyboardType: TextInputType.name,
          onSubmit: (string) => inputName = string,
        ),
        SizedBox(width: width(30)),
        InputEditText(
          Strings.idCardTxt,
          keyboardType: TextInputType.number,
          onSubmit: (string) => inputIdCard = string,
        ),
        SizedBox(width: width(30)),
        InputEditText(
          Strings.personNoTxt,
          onSubmit: (string) => inputPersonNum = string,
        ),
        SizedBox(width: width(30)),
        InputEditText(
          Strings.socialCardTxt,
          onSubmit: (string) => inputSocialCard = string,
        ),
        SizedBox(width: width(30)),
        Container(
          color: Colours.u_2787de,
          width: 50,
          height: 26,
          child: OutlineButton(
            padding: EdgeInsets.all(0),
            child: Text(
              Strings.searchTxt,
              style: TextStyles.textSize12AndWhite,
            ),
            onPressed: () {
              firstRequest = true;
              _requestListBasicInfo(1);
            },
          ),
        )
      ],
    );
  }

  Widget getItem(int index) {
    UserBean bean = _userList[index];
    return Container(
      height: 28,
      color: (index % 2 == 0) ? Colors.white : Colours.u_eff7fb,
      child: Row(
        children: <Widget>[
          Gaps.hLine,
          Expanded(
            //序号
            flex: 1,
            child: Text(
              '${index + 1}',
              style: TextStyles.textSize12,
              textAlign: TextAlign.center,
            ),
          ),
          Gaps.hLine,
          Expanded(
            //姓名
            flex: 2,
            child: Text(
              bean?.name,
              style: TextStyles.textSize12,
              textAlign: TextAlign.center,
            ),
          ),
          Gaps.hLine,
          Expanded(
            //身份证号
            flex: 4,
            child: Text(
              bean?.idCardNo,
              style: TextStyles.textSize12,
              textAlign: TextAlign.center,
            ),
          ),
          Gaps.hLine,
          Expanded(
            //个人编号
            flex: 3,
            child: Text(
              bean?.basicCode,
              style: TextStyles.textSize12,
              textAlign: TextAlign.center,
            ),
          ),
          Gaps.hLine,
          Expanded(
            //社保卡号
            flex: 3,
            child: Text(
              bean?.socialSecNo,
              style: TextStyles.textSize12,
              textAlign: TextAlign.center,
            ),
          ),
          Gaps.hLine,
          Expanded(
            flex: 2,
            child: FlatButton(
              onPressed: () => NavigatorUtils.push(
                  context, RouterPath.personInfoQueryDetailRoute),
              child: Gaps.operateBtn,
            ),
          ),
          Gaps.hLine,
        ],
      ),
    );
  }

  ///下拉刷新
  Future _refreshData() async {
    _userList.clear();
    _page = 1;
    await _requestListBasicInfo(_page);
    if (!_enableControlFinish) {
      _refreshController
        ..resetLoadState()
        ..finishRefresh();
    }
  }

  ///上拉加载
  Future _loadMoreData() async {
    _page++;
    await _requestListBasicInfo(_page);
    if (!_enableControlFinish) {
      _refreshController..finishLoad(noMore: _page > _count);
    }
  }
}
